\ifx\locallinewidth\undefined\newlength{\locallinewidth}\fi
\setlength{\locallinewidth}{\linewidth}
\section{\module{ctypes} --- A foreign function library for Python.}
\declaremodule{standard}{ctypes}
\moduleauthor{Thomas Heller}{theller@python.net}
\modulesynopsis{A foreign function library for Python.}
\versionadded{2.5}
% maybe make title "ctypes --- A foreign function library for Python" 
% or use pep reader and 


\subsection{ctypes tutorial\label{ctypes-ctypes-tutorial}}

This tutorial describes version 0.9.9 of \code{ctypes}.
Since older versions are quite common, I'll mention major differences
when needed.


\subsubsection{Loading dynamic link libraries\label{ctypes-loading-dynamic-link-libraries}}

\code{ctypes} exports the \var{cdll}, and on Windows also \var{windll} and
\var{oledll} objects to load dynamic link libraries.

You load libraries by accessing them as attributes of these objects.
\var{cdll} loads libraries which export functions using the standard
\code{cdecl} calling convention, while \var{windll} libraries call
functions using the \code{stdcall} calling convention. \var{oledll} also
uses the \code{stdcall} calling convention, and assumes the functions
return a Windows \class{HRESULT} error code. The error code is used to
automatically raise \class{WindowsError} Python exceptions when the
function call fails.

Here are some examples for Windows, note that \code{msvcrt} is the MS
standard C library containing most standard C functions, and uses the
cdecl calling convention:
\begin{verbatim}
>>> from ctypes import *
>>> print windll.kernel32
<WinDLL 'kernel32', handle 7c800000 at ...>
>>> print cdll.msvcrt
<CDLL 'msvcrt', handle 77be0000 at ...>
\end{verbatim}

In principle the same way should work on Linux, but most of the time
it seems required to specify the search path in this way. So this
example shows also how to load libraries by specifying their
filename:
\begin{verbatim}
>>> from ctypes import *
>>> libc = cdll.load("/lib/libc.so.6") # doctest: +SKIP
<CDLL '/lib/libc.so.6', handle 40018c28 at 4019978c>
>>>
\end{verbatim}

\textbf{Note:} in older versions, the \method{LoadLibrary} method should be used
instead.

This tutorial uses windows in its examples, however, functions from
the standard C library like \code{strchr} and \code{printf} should also work
on Linux and other systems.


\subsubsection{Accessing functions from loaded dlls\label{ctypes-accessing-functions-from-loaded-dlls}}

Functions are accessed as attributes of dll objects:
\begin{verbatim}
>>> from ctypes import *
>>> print cdll.msvcrt.printf
<_FuncPtr object at 0x...>
>>> print windll.kernel32.GetModuleHandleA
<_FuncPtr object at 0x...>
>>> print windll.kernel32.MyOwnFunction
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
\end{verbatim}

Note that win32 system dlls like \code{kernel32} and \code{user32} often
export ANSI as well as UNICODE versions of a function. The UNICODE
version is exported with an \code{W} appended to the name, while the ANSI
version is exported with an \code{A} appended to the name. The win32
\code{GetModuleHandle} function, which returns a \emph{module handle} for a
given module name, has the following C prototype, and a macro is used
to expose one of them as \code{GetModuleHandle} depending on whether
UNICODE is defined or not:
\begin{verbatim}
/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
\end{verbatim}

\var{windll} does not try to select one of them by magic, you must
access the version you need by specifying \code{GetModuleHandleA} or
\code{GetModuleHandleW} explicitely, and then call it with normal strings
or unicode strings respectively.

Sometimes, dlls export functions with names which aren't valid Python
identifiers, like \code{"??2@YAPAXI@Z"}. In this case you have to use
\code{getattr} to retrieve the function (XXX Better example?):
\begin{verbatim}
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")
<_FuncPtr object at 0x...>
>>>
\end{verbatim}


\subsubsection{Calling functions\label{ctypes-calling-functions}}

You can call these functions like any other Python callable. This
example uses the \code{time()} function, which returns system time in
seconds since the \UNIX{} epoch, and the \code{GetModuleHandleA()} function,
which returns a win32 module handle.

This example calls both functions with a NULL pointer (\code{None} should
be used as the NULL pointer):
\begin{verbatim}
>>> from ctypes import *
>>> print cdll.msvcrt.time(None)
1143...
>>> print hex(windll.kernel32.GetModuleHandleA(None))
0x1d000000
\end{verbatim}

\code{ctypes} tries to protect you from calling functions with the wrong
number of arguments.  Unfortunately this only works on Windows.  It
does this by examining the stack after the function returns:
\begin{verbatim}
>>> windll.kernel32.GetModuleHandleA()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>> windll.kernel32.GetModuleHandleA(0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>
\end{verbatim}

On Windows, \code{ctypes} uses win32 structured exception handling to
prevent crashes from general protection faults when functions are
called with invalid argument values:
\begin{verbatim}
>>> windll.kernel32.GetModuleHandleA(32)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
WindowsError: exception: access violation reading 0x00000020
>>>
\end{verbatim}

There are, however, enough ways to crash Python with \code{ctypes}, so
you should be careful anyway.

Python integers, strings and unicode strings are the only objects that
can directly be used as parameters in these function calls.

Before we move on calling functions with other parameter types, we
have to learn more about \code{ctypes} data types.


\subsubsection{Simple data types\label{ctypes-simple-data-types}}

\code{ctypes} defines a number of primitive C compatible data types :
\begin{quote}
\begin{tableiii}{l|l|l}{textrm}
{
ctypes type
}
{
C type
}
{
Python type
}
\lineiii{
\class{c{\_}char}
}
{
\code{char}
}
{
character
}
\lineiii{
\class{c{\_}byte}
}
{
\code{char}
}
{
integer
}
\lineiii{
\class{c{\_}ubyte}
}
{
\code{unsigned char}
}
{
integer
}
\lineiii{
\class{c{\_}short}
}
{
\code{short}
}
{
integer
}
\lineiii{
\class{c{\_}ushort}
}
{
\code{unsigned short}
}
{
integer
}
\lineiii{
\class{c{\_}int}
}
{
\code{int}
}
{
integer
}
\lineiii{
\class{c{\_}uint}
}
{
\code{unsigned int}
}
{
integer
}
\lineiii{
\class{c{\_}long}
}
{
\code{long}
}
{
integer
}
\lineiii{
\class{c{\_}ulong}
}
{
\code{unsigned long}
}
{
long
}
\lineiii{
\class{c{\_}longlong}
}
{
\code{{\_}{\_}int64} or
\code{long long}
}
{
long
}
\lineiii{
\class{c{\_}ulonglong}
}
{
\code{unsigned {\_}{\_}int64} or
\code{unsigned long long}
}
{
long
}
\lineiii{
\class{c{\_}float}
}
{
\code{float}
}
{
float
}
\lineiii{
\class{c{\_}double}
}
{
\code{double}
}
{
float
}
\lineiii{
\class{c{\_}char{\_}p}
}
{
\code{char *}
(NUL terminated)
}
{
string or
\code{None}
}
\lineiii{
\class{c{\_}wchar{\_}p}
}
{
\code{wchar{\_}t *}
(NUL terminated)
}
{
unicode or
\code{None}
}
\lineiii{
\class{c{\_}void{\_}p}
}
{
\code{void *}
}
{
integer or
\code{None}
}
\end{tableiii}
\end{quote}

All these types can be created by calling them with an optional
initializer of the correct type and value:
\begin{verbatim}
>>> c_int()
c_long(0)
>>> c_char_p("Hello, World")
c_char_p('Hello, World')
>>> c_ushort(-3)
c_ushort(65533)
>>>
\end{verbatim}

Since these types are mutable, their value can also be changed
afterwards:
\begin{verbatim}
>>> i = c_int(42)
>>> print i
c_long(42)
>>> print i.value
42
>>> i.value = -99
>>> print i.value
-99
>>>
\end{verbatim}

Assigning a new value to instances of the pointer types \class{c{\_}char{\_}p},
\class{c{\_}wchar{\_}p}, and \class{c{\_}void{\_}p} changes the \emph{memory location} they
point to, \emph{not the contents} of the memory block (of course not,
because Python strings are immutable):
\begin{verbatim}
>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> c_s.value = "Hi, there"
>>> print c_s
c_char_p('Hi, there')
>>> print s                 # first string is unchanged
Hello, World
\end{verbatim}

You should be careful, however, not to pass them to functions
expecting pointers to mutable memory. If you need mutable memory
blocks, ctypes has a \code{create{\_}string{\_}buffer} function which creates
these in various ways.  The current memory block contents can be
accessed (or changed) with the \code{raw} property, if you want to access
it as NUL terminated string, use the \code{string} property:
\begin{verbatim}
>>> from ctypes import *
>>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
>>> print sizeof(p), repr(p.raw)
3 '\x00\x00\x00'
>>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
>>> print sizeof(p), repr(p.raw)
6 'Hello\x00'
>>> print repr(p.value)
'Hello'
>>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer
>>> print sizeof(p), repr(p.raw)
10 'Hello\x00\x00\x00\x00\x00'
>>> p.value = "Hi"
>>> print sizeof(p), repr(p.raw)
10 'Hi\x00lo\x00\x00\x00\x00\x00'
>>>
\end{verbatim}

The \code{create{\_}string{\_}buffer} function replaces the \code{c{\_}buffer}
function (which is still available as an alias), as well as the
\code{c{\_}string} function from earlier ctypes releases.  To create a
mutable memory block containing unicode characters of the C type
\code{wchar{\_}t} use the \code{create{\_}unicode{\_}buffer} function.


\subsubsection{Calling functions, continued\label{ctypes-calling-functions-continued}}

Note that printf prints to the real standard output channel, \emph{not} to
\code{sys.stdout}, so these examples will only work at the console
prompt, not from within \emph{IDLE} or \emph{PythonWin}:
\begin{verbatim}
>>> from ctypes import *; printf = cdll.msvcrt.printf
>>> printf("Hello, %s\n", "World!") # doctest: +SKIP
Hello, World!
14
>>> printf("Hello, %S", u"World!") # doctest: +SKIP
Hello, World!
14
>>> printf("%d bottles of beer\n", 42) # doctest: +SKIP
42 bottles of beer
19
>>> printf("%f bottles of beer\n", 42.5) # doctest: +SKIP
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
>>>
\end{verbatim}

As has been mentioned before, all Python types except integers,
strings, and unicode strings have to be wrapped in their corresponding
\code{ctypes} type, so that they can be converted to the required C data
type:
\begin{verbatim}
>>> from ctypes import *
>>> printf = cdll.msvcrt.printf
>>> printf("An int %d, a double %f\n", 1234, c_double(3.14)) # doctest: +SKIP
Integer 1234, double 3.1400001049
34
>>>
\end{verbatim}


\subsubsection{Calling functions with your own custom data types\label{ctypes-calling-functions-with-own-custom-data-types}}

You can also customize \code{ctypes} argument conversion to allow
instances of your own classes be used as function arguments.
\code{ctypes} looks for an \member{{\_}as{\_}parameter{\_}} attribute and uses this as
the function argument. Of course, it must be one of integer, string,
or unicode:
\begin{verbatim}
>>> class Bottles(object):
...     def __init__(self, number):
...         self._as_parameter_ = number
...
>>> bottles = Bottles(42)
>>> from ctypes import *
>>> printf = cdll.msvcrt.printf
>>> printf("%d bottles of beer\n", bottles) # doctest: +SKIP
42 bottles of beer
19
>>>
\end{verbatim}

If you don't want to store the instance's data in the
\member{{\_}as{\_}parameter{\_}} instance variable, you could define a \code{property}
which makes the data avaiblable.


\subsubsection{Specifying the required argument types (function prototypes)\label{ctypes-specifying-required-argument-types}}

It is possible to specify the required argument types of functions
exported from DLLs by setting the \member{argtypes} attribute.

\member{argtypes} must be a sequence of C data types (the \code{printf}
function is probably not a good example here, because it takes a
variable number and different types of parameters depending on the
format string, on the other hand this is quite handy to experiment
with this feature):
\begin{verbatim}
>>> from ctypes import *
>>> printf = cdll.msvcrt.printf
>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2) # doctest: +SKIP
String 'Hi', Int 10, Double 2.200000
\end{verbatim}

Specifying a format protects against incompatible argument types (just
as a prototype for a C function), and tries to convert the arguments
to valid types:
\begin{verbatim}
>>> printf("%d %d %d", 1, 2, 3) # doctest: +SKIP
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: string expected instead of int instance
>>> printf("%s %d %f", "X", 2, 3) # doctest: +SKIP
X 2 3.00000012
>>>
\end{verbatim}

If you have defined your own classes which you pass to function calls,
you have to implement a \method{from{\_}param} class method for them to be
able to use them in the \member{argtypes} sequence. The \method{from{\_}param}
class method receives the Python object passed to the function call,
it should do a typecheck or whatever is needed to make sure this
object is acceptable, and then return the object itself, it's
\member{{\_}as{\_}parameter{\_}} attribute, or whatever you want to pass as the C
function argument in this case. Again, the result should be an
integer, string, unicode, a \code{ctypes} instance, or something having
the \member{{\_}as{\_}parameter{\_}} attribute.


\subsubsection{Return types\label{ctypes-return-types}}

By default functions are assumed to return integers.  Other return
types can be specified by setting the \member{restype} attribute of the
function object.

Here is a more advanced example, it uses the strchr function, which
expects a string pointer and a char, and returns a pointer to a
string:
\begin{verbatim}
>>> from ctypes import *
>>> strchr = cdll.msvcrt.strchr
>>> strchr("abcdef", ord("d")) # doctest: +SKIP
8059983
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string
>>> strchr("abcdef", ord("d"))
'def'
>>> print strchr("abcdef", ord("x"))
None
>>>
\end{verbatim}

If you want to avoid the \code{ord("x")} calls above, you can set the
\member{argtypes} attribute, and the second argument will be converted from
a single character Python string into a C char:
\begin{verbatim}
>>> from ctypes import *
>>> msvcrt = cdll.msvcrt
>>> msvcrt.strchr.restype = c_char_p
>>> msvcrt.strchr.argtypes = [c_char_p, c_char]
>>> msvcrt.strchr("abcdef", "d")
'def'
>>> msvcrt.strchr("abcdef", "def")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ArgumentError: argument 2: exceptions.TypeError: one character string expected
>>> print msvcrt.strchr("abcdef", "x")
None
>>> msvcrt.strchr("abcdef", "d")
'def'
>>>
\end{verbatim}

XXX Mention the \member{errcheck} protocol...

You can also use a callable Python object (a function or a class for
example) as the \member{restype} attribute.  It will be called with the
\code{integer} the C function returns, and the result of this call will
be used as the result of your function call. This is useful to check
for error return values and automatically raise an exception:
\begin{verbatim}
>>> from ctypes import *
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA
>>> def ValidHandle(value):
...     if value == 0:
...         raise WinError()
...     return value
...
>>>
>>> GetModuleHandle.restype = ValidHandle
>>> GetModuleHandle(None)
486539264
>>> GetModuleHandle("something silly") # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in ValidHandle
WindowsError: [Errno 126] The specified module could not be found.
>>>
\end{verbatim}

\code{WinError} is a function which will call Windows \code{FormatMessage()}
api to get the string representation of an error code, and \emph{returns}
an exception.  \code{WinError} takes an optional error code parameter, if
no one is used, it calls \function{GetLastError()} to retrieve it.


\subsubsection{Passing pointers (or: passing parameters by reference)\label{ctypes-passing-pointers}}

Sometimes a C api function expects a \emph{pointer} to a data type as
parameter, probably to write into the corresponding location, or if
the data is too large to be passed by value. This is also known as
\emph{passing parameters by reference}.

\code{ctypes} exports the \function{byref} function which is used to pass
parameters by reference.  The same effect can be achieved with the
\code{pointer} function, although \code{pointer} does a lot more work since
it constructs a real pointer object, so it is faster to use \function{byref}
if you don't need the pointer object in Python itself:
\begin{verbatim}
>>> from ctypes import *
>>> msvcrt = cdll.msvcrt
>>> i = c_int()
>>> f = c_float()
>>> s = create_string_buffer('\000' * 32)
>>> print i.value, f.value, repr(s.value)
0 0.0 ''
>>> msvcrt.sscanf("1 3.14 Hello", "%d %f %s",
...               byref(i), byref(f), s)
3
>>> print i.value, f.value, repr(s.value)
1 3.1400001049 'Hello'
>>>
\end{verbatim}


\subsubsection{Structures and Unions\label{ctypes-structures-unions}}

Structures and unions must derive from the \class{Structure} and \class{Union}
base classes which are defined in the \code{ctypes} module. Each subclass
must define a \member{{\_}fields{\_}} attribute.  \member{{\_}fields{\_}} must be a list of
\emph{2-tuples}, containing a \emph{field name} and a \emph{field type}.

The field type must be a \code{ctypes} type like \class{c{\_}int}, or any other
derived \code{ctypes} type: structure, union, array, pointer.

Here is a simple example of a POINT structure, which contains two
integers named \code{x} and \code{y}, and also shows how to initialize a
structure in the constructor:
\begin{verbatim}
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = [("x", c_int),
...                 ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print point.x, point.y
10 20
>>> point = POINT(y=5)
>>> print point.x, point.y
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: too many initializers
>>>
\end{verbatim}

You can, however, build much more complicated structures. Structures
can itself contain other structures by using a structure as a field
type.

Here is a RECT structure which contains two POINTs named \code{upperleft}
and \code{lowerright}
\begin{verbatim}
>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print rc.upperleft.x, rc.upperleft.y
0 5
>>> print rc.lowerright.x, rc.lowerright.y
0 0
>>>
\end{verbatim}

Nested structures can also be initialized in the constructor in
several ways:
\begin{verbatim}
>>> r = RECT(POINT(1, 2), POINT(3, 4))
>>> r = RECT((1, 2), (3, 4))
\end{verbatim}

XXX Fields descriptors can be retrieved from the \emph{class}, they
have readonly \code{size} and \code{offset} attributes describing the size
in bytes and the offset of this field from the beginning of the
internal memory buffer:
\begin{verbatim}
>>> print POINT.x.size, POINT.x.offset
4 0
>>> print POINT.y.size, POINT.y.offset
4 4
>>>
\end{verbatim}

By default, Structure and Union fields are aligned in the same way the
C compiler does it. It is possible to override this behaviour be
specifying a \member{{\_}pack{\_}} class attribute in the subclass
definition. This must be set to a positive integer and specifies the
maximum alignment for the fields. This is what \code{{\#}pragma pack(n)}
also does in MSVC.

\textbf{New in version 0.6.2}: Structures and unions can also be passed \emph{by
value} to function calls.


\subsubsection{Arrays\label{ctypes-arrays}}

Arrays are sequences, containing a fixed number of instances of the
same type.

The recommended way to create array types is by multiplying a data
type with a positive integer:
\begin{verbatim}
TenPointsArrayType = POINT * 10
\end{verbatim}

Here is an example of an somewhat artifical data type, a structure
containing 4 POINTs among other stuff:
\begin{verbatim}
>>> from ctypes import *
>>> class POINT(Structure):
...    _fields_ = ("x", c_int), ("y", c_int)
...
>>> class MyStruct(Structure):
...    _fields_ = [("a", c_int),
...                ("b", c_float),
...                ("point_array", POINT * 4)]
>>>
>>> print len(MyStruct().point_array)
4
\end{verbatim}

Instances are created in the usual way, by calling the class:
\begin{verbatim}
arr = TenPointsArrayType()
for pt in arr:
    print pt.x, pt.y
\end{verbatim}

The above code print a series of \code{0 0} lines, because the array
contents is initialized to zeros.

Initializers of the correct type can also be specified:
\begin{verbatim}
>>> from ctypes import *
>>> TenIntegers = c_int * 10
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> print ii
<c_long_Array_10 object at 0x...>
>>> for i in ii: print i,
...
1 2 3 4 5 6 7 8 9 10
>>>
\end{verbatim}


\subsubsection{Pointers\label{ctypes-pointers}}

Pointer instances are created by calling the \code{pointer} function on a
\code{ctypes} type:
\begin{verbatim}
>>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>>
\end{verbatim}

XXX XXX Not correct: use indexing, not the contents atribute

Pointer instances have a \code{contents} attribute which returns the
ctypes' type pointed to, the \code{c{\_}int(42)} in the above case:
\begin{verbatim}
>>> pi.contents
c_long(42)
>>>
\end{verbatim}

Assigning another \class{c{\_}int} instance to the pointer's contents
attribute would cause the pointer to point to the memory location
where this is stored:
\begin{verbatim}
>>> pi.contents = c_int(99)
>>> pi.contents
c_long(99)
>>>
\end{verbatim}

Pointer instances can also be indexed with integers:
\begin{verbatim}
>>> pi[0]
99
>>>
\end{verbatim}

XXX What is this???
Assigning to an integer index changes the pointed to value:
\begin{verbatim}
>>> i2 = pi[0]
>>> i2
99
>>> pi[0] = 22
>>> i2
99
>>>
\end{verbatim}

It is also possible to use indexes different from 0, but you must know
what you're doing when you use this: You access or change arbitrary
memory locations when you do this. Generally you only use this feature
if you receive a pointer from a C function, and you \emph{know} that the
pointer actually points to an array instead of a single item.


\subsubsection{Pointer classes/types\label{ctypes-pointer-classestypes}}

Behind the scenes, the \code{pointer} function does more than simply
create pointer instances, it has to create pointer \emph{types} first.
This is done with the \code{POINTER} function, which accepts any
\code{ctypes} type, and returns a new type:
\begin{verbatim}
>>> from ctypes import *
>>> PI = POINTER(c_int)
>>> PI
<class 'ctypes.LP_c_long'>
>>> PI(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: expected c_long instead of int
>>> PI(c_int(42))
<ctypes.LP_c_long object at 0x...>
>>>
\end{verbatim}


\subsubsection{Incomplete Types\label{ctypes-incomplete-types}}

\textbf{Note:} This code seems to work in older versions, but the past
convention was to use the now deprecated \code{SetPointerType} function.
If you have an older version and the following example does not work
for you, try looking up that function.

\emph{Incomplete Types} are structures, unions or arrays whose members are
not yet specified. In the \code{ctypes} context, you can create types
representing pointers to these incomplete types by passing their name
(as a string) to the POINTER function, and complete the result
subclass later.

Consider this example (C-code):
\begin{verbatim}
struct cell;

struct {
    char *name;
    struct cell *next;
} cell;
\end{verbatim}

The straightforward translation into ctypes code would be this, but it
does not work:
\begin{verbatim}
>>> class cell(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("next", POINTER(cell))]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in cell
NameError: name 'cell' is not defined
>>>
\end{verbatim}

because the new \code{class cell} is not available in the class statement
itself.

We can do it by creating an \emph{incomplete type}. Just leave out the
\member{{\_}fields{\_}} declaration and fill it up later:
\begin{verbatim}
>>> from ctypes import *
>>> class cell(Structure):
...     pass
...
>>> cell._fields_ = [("name", c_char_p),
...                  ("next", POINTER(cell))]
>>>
\end{verbatim}

Lets try it. We create two instances of \code{cell}, and let them point
to each other, and finally follow the pointer chain a few times:
\begin{verbatim}
>>> c1 = cell()
>>> c1.name = "foo"
>>> c2 = cell()
>>> c2.name = "bar"
>>> c1.next = pointer(c2)
>>> c2.next = pointer(c1)
>>> p = c1
>>> for i in range(8):
...     print p.name,
...     p = p.next[0]
...
foo bar foo bar foo bar foo bar
>>>
\end{verbatim}


\subsubsection{Callback functions\label{ctypes-callback-functions}}

(This example is too long, I should have used a shorter array)

\code{ctypes} allows to create C callable function pointers from Python
callables. These are sometimes called \emph{callback functions}.

First, you must create a class for the callback function, the class
knows the calling convention, the result type the function has to
return, and the number and types of the arguments this function will
receive.

\code{ctypes} provides the CFUNCTYPE factory function to create types for
callback functions using the normal cdecl calling convention, and, on
Windows, the WINFUNCTYPE factory function to create types for callback
functions using the stdcall calling convention.

Both of these factory functions are called with the result type as
first argument, and the callback functions expected argument types as
the remaining arguments.

I will present an example here which uses the standard C library's
\function{qsort} function, this is used to sort items with the help of a
callback function. \function{qsort} will be used to sort an array of
integers:
\begin{verbatim}
>>> from ctypes import *
>>> IntArray5 = c_int * 5
>>> ia = IntArray5(5, 1, 7, 33, 99)
>>> qsort = cdll.msvcrt.qsort
>>>
\end{verbatim}

\function{qsort} must be called with a pointer to the data to sort, the
number of items in the data array, the size of one item, and the sort
function, which is the callback. The callback function will then be
called with two pointers to items, and it must return a negative
integer if the first item is smaller than the second, a 0 if they are
equal, and a positive integer else.

So our callback function receives pointers to integers, and must
return an integer. First we create the \code{type} for the callback
function:
\begin{verbatim}
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
>>>
\end{verbatim}

For the first implementation of the callback function, we simply print
the arguments we get, and return 0 (incremental development):
\begin{verbatim}
>>> def py_cmp_func(a, b):
...     print "py_cmp_func", a, b
...     return 0
...
>>>
\end{verbatim}

Create the C callable function:
\begin{verbatim}
>>> cmp_func = CMPFUNC(py_cmp_func)
>>>
\end{verbatim}

And we're ready to go:
\begin{verbatim}
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
py_cmp_func <ctypes.LP_c_long object at 0x00C70AD0> <ctypes.LP_c_long object at 0x00C70B20>
-1
>>>
\end{verbatim}

We know how to access the contents of a pointer, so lets redefine our callback:
\begin{verbatim}
>>> def py_cmp_func(a, b):
...     print "py_cmp_func", a[0], b[0]
...     return 0
...
>>> cmp_func = CMPFUNC(py_cmp_func)
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
py_cmp_func 7 1
py_cmp_func 33 1
py_cmp_func 99 1
py_cmp_func 5 1
py_cmp_func 7 5
py_cmp_func 33 5
py_cmp_func 99 5
py_cmp_func 7 99
py_cmp_func 33 99
py_cmp_func 7 33
-1
>>>
\end{verbatim}

Ah, we're nearly done! Last refinements:
\begin{verbatim}
>>> def py_cmp_func(a, b):
...     print "py_cmp_func", a[0], b[0]
...     return a[0] - b[0]
...
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))
py_cmp_func 33 7
py_cmp_func 99 33
py_cmp_func 5 99
py_cmp_func 1 99
py_cmp_func 33 7
py_cmp_func 1 33
py_cmp_func 5 33
py_cmp_func 5 7
py_cmp_func 1 7
py_cmp_func 5 1
-1
>>>
\end{verbatim}

So, is our array sorted now:
\begin{verbatim}
>>> for i in ia: print i,
...
1 5 7 33 99
>>>
\end{verbatim}

Yep, it worked!

\textbf{Important note for callback functions:}

Make sure you keep references to CFUNCTYPE objects as long as they are
used from C code. ctypes doesn't, and if you don't, they may be
garbage collected, crashing your program when a callback is made.


\subsubsection{Accessing values exported from dlls\label{ctypes-accessing-values-exported-from-dlls}}

Sometimes, a dll not only exports functions, it also exports
values. Examples in the Python dll itself are the \code{Py{\_}OptimizeFlag},
an integer set to 0, 1, or 2, depending on the \programopt{-O} or \programopt{-OO} flag
given on startup.

Starting with version 0.6.1, \code{ctypes} can access values like this
with the \method{in{\_}dll} class methods of the types. The following examples
only work on Windows:
\begin{verbatim}
>>> from ctypes import *
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
>>> print opt_flag
c_long(0)
>>>
\end{verbatim}

If the interpreter would have been started with \programopt{-O}, the sample
would have printed \code{c{\_}long(1)}, or \code{c{\_}long(2)} if \programopt{-OO} would have
been specified.

A somewhat extended example which also demontrates the use of pointers
accesses the \code{PyImport{\_}FrozenModules} pointer exported by Python.

Quoting the Python docs: \emph{This pointer is initialized to point to an
array of ``struct {\_}frozen`` records, terminated by one whose members
are all NULL or zero. When a frozen module is imported, it is searched
in this table. Third-party code could play tricks with this to provide
a dynamically created collection of frozen modules.}

So manipulating this pointer could even prove useful. To restrict the
example size, we show only how this table can be read with
\code{ctypes}:
\begin{verbatim}
>>> from ctypes import *
>>>
>>> class struct_frozen(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("code", POINTER(c_ubyte)),
...                 ("size", c_int)]
...
>>>
\end{verbatim}

XXX Should use pythonapi instead!!!
We have \code{loaded} the Python dll and defined the \code{struct {\_}frozen}
data type, so we can get the pointer to the table:
\begin{verbatim}
>>> FrozenTable = POINTER(struct_frozen)
>>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
>>>
\end{verbatim}

Since \code{table} is a \code{pointer} to the \code{struct{\_}frozen} records, we
can iterate over it, we just have to make sure that our loop
terminates, because pointers have no size. Sooner or later it would
probably crash with an access violation or whatever, so it's better to
break out of the loop when we hit the NULL entry:
\begin{verbatim}
>>> for item in table:
...    print item.name, item.size
...    if item.name is None:
...        break
...
__hello__ 104
__phello__ -104
__phello__.spam 104
None 0
>>>
\end{verbatim}

The fact that standard Python has a frozen module and a frozen package
(indicated by the negative size member) is not wellknown, AFAIK it is
used for testing. Try it out with \code{import {\_}{\_}hello{\_}{\_}} for example.

XXX Describe how to access the \var{code} member fields, which contain
the byte code for the modules.


\subsubsection{Surprises\label{ctypes-surprises}}

There are some corners in \code{ctypes} where you may be expect something
else than what actually happens.

Consider the following example:
\begin{verbatim}
>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class RECT(Structure):
...     _fields_ = ("a", POINT), ("b", POINT)
...
>>> p1 = POINT(1, 2)
>>> p2 = POINT(3, 4)
>>> rc = RECT(p1, p2)
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1 2 3 4
>>> # now swap the two points
>>> rc.a, rc.b = rc.b, rc.a
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
3 4 3 4
\end{verbatim}

Hm. We certainly expected the last statement to print \code{3 4 1 2}.
What happended? Here are the steps of the \code{rc.a, rc.b = rc.b, rc.a}
line above:
\begin{verbatim}
>>> temp0, temp1 = rc.b, rc.a
>>> rc.a = temp0
>>> rc.b = temp1
\end{verbatim}

Note that \code{temp0} and \code{temp1} are objects still using the internal
buffer of the \code{rc} object above. So executing \code{rc.a = temp0}
copies the buffer contents of \code{temp0} into \code{rc} 's buffer.  This,
in turn, changes the contents of \code{temp1}. So, the last assignment
\code{rc.b = temp1}, doesn't have the expected effect.

Keep in mind that retrieving subobjects from Structure, Unions, and
Arrays doesn't \emph{copy} the subobject, it does more retrieve a wrapper
object accessing the root-object's underlying buffer.


\subsubsection{Bugs, ToDo and non-implemented things\label{ctypes-bugs-todo-non-implemented-things}}

\begin{datadescni}{XXX Wrong}
Bitfields are not implemented.

Enumeration types are not implemented. You can do it easily
yourself, using \class{c{\_}int} as the base class.

\code{long double} is not implemented.
\end{datadescni}
% no longer true:  You cannot pass structures to functions as arguments, and you
% cannot set them as return type (only pointers). 
% no longer true?   Callback functions implemented in Python can *only* return integers. 
% Local Variables:
% compile-command: "make_html"
% End: 


\subsection{ctypes manual\label{ctypes-ctypes-manual}}


\subsubsection{Shared Libraries, DLLs\label{ctypes-shared-libraries-dlls}}

Shared libraries are accessed when compiling/linking a program, and
when the program is run. The purpose of the \method{find} method is to
locate a library in a way similar to what the compiler does (on
platforms with several versions of a shared library the most recent
should be loaded), while \method{load} acts like when a program is run, and
uses the runtime loader directly. \method{load{\_}version} works like \method{load}
but tries to be platform independent (for cases where this makes
sense). Loading via attribute access is a shorthand notation
especially usefull for interactive use, it is equivalent to calling
\method{load{\_}version} with no version specified.


\subsubsection{class LibraryLoader\label{ctypes-class-libraryloader}}

Instances of \class{LibraryLoader} are used to load shared libraries.
Usually there is no need to create a libraryloader, instead one of the
predefined loaders should be used.

Libraryloaders have the following methods:

\begin{funcdesc}{find}{name, mode=None}
Try to find a library, load and return it.  \var{name} is the
library name without any prefix like \var{lib}, suffix like \code{.so},
\code{.dylib} or version number (this is the form used for the posix
linker option \programopt{-l}).

\var{mode} allows to override the default flags passed to the
\code{dlopen()} function, ignored on Windows.

On Windows, this method does exactly the same as the \method{load}
method.

On other platforms, this function might call other programs like
the compiler to find the library.  When using ctypes to write a
shared library wrapping, consider using \method{load{\_}version} or
\method{load} instead.
\end{funcdesc}

\begin{funcdesc}{load_version}{name, version=None, mode=None}
Build a system dependent filename from \var{name} and optionally
\var{version}, then load and return it.  \var{name} is the library
name without any prefix like \var{lib} and suffix like \code{.so} or
\code{.dylib}.  This method should be used if a library is available
on different platforms, using the particular naming convention of
each platform.

\var{mode} allows to override the default flags passed to the
\code{dlopen()} function, ignored on Windows.

Example: calling \code{loader.load{\_}version('z', '1.1.3')} would
possibly load \code{/usr/lib/libz.1.1.3.dylib} on Mac OS X, or
\code{/lib/libz.so.1.1.3} on a Linux system.
\end{funcdesc}

\begin{funcdesc}{load}{libname, mode=None}
Load and return the library with the given libname.  On most
systems \var{libname} is the filename of the shared library; when
it's not a pathname it will be searched in a system dependent list
of locations (on many systems additional search paths can be
specified by an environment variable).  Sometimes the file
extension (like \code{.dll} on Windows) can be omitted.

\var{mode} allows to override the default flags passed to the
\code{dlopen()} function.  \var{RTLD{\_}LOCAL} and \var{RTLD{\_}GLOBAL} are
typical values.  On Windows, \var{mode} is ignored.
\end{funcdesc}

\begin{funcdesc}{load_library}{pathname, mode=None}
Load and return the library with the given pathname.  This method
passes the \code{pathname} directly to the underlying \code{dlopen} or
\method{LoadLibrary} function.

\var{mode} allows to override the default flags passed to the
\code{dlopen()} function.  \var{RTLD{\_}LOCAL} and \var{RTLD{\_}GLOBAL} are
typical values.  On Windows, \var{mode} is ignored.
\end{funcdesc}

\begin{funcdesc}{LoadLibrary}{pathname, mode=None}
This is an alias for the \method{load{\_}library} method documented above,
maintained for backwards comatibility only.
\end{funcdesc}

Libaries can also be loaded by accessing them as attributes of the
loader instance, internally this calls \method{load{\_}version} without
specifying \var{version} or \var{mode}.  Obviously this only works for
libraries with names that are valid Python identifiers, and when the
name does not start with a \code{{\_}} character.


\subsubsection{Predefined library loaders\label{ctypes-predefined-library-loaders}}

ctypes provides some LibraryLoader instances, the differences between
them are the calling conventions the functions will use and the
default return type of the functions.  All these loaders use the
\var{RTLD{\_}LOCAL} mode flag.

Functions can be accessed as named attributes of loaded libraries.

On Windows, structured exception handling is used around the function
call to protect Python from crashing in case you pass invalid
parameters to the function.

\var{cdll}
\begin{quote}

Functions provided by libraries loaded using the \var{cdll} loader
will be called with the standard C calling convention, and have a
default return type of \code{int}.  ctypes releases the Python global
interpreter lock (GIL) just before calling the foreign function,
and reacquires it before returing, so other threads are able to
run.
\end{quote}

\var{windll}
\begin{quote}

Windows only.  Functions provided by libraries loaded by
\var{windll} will be called using the Windows \code{{\_}{\_}stdcall} calling
convention.  ctypes can detect when the wrong number
of parameters has been passed to the function call by examining
the stack pointer before and after the function call.  If the
wrong parameter count was used, an exception is raised (although
the function really \emph{has} been called).  The return value of the
function is lost in this case.  Again, the GIL is released during
the duration of the function call.
\end{quote}

\var{oledll}
\begin{quote}

Windows only.  \var{oledll} behaves in the same way as \var{windll},
except that the called function is expected to return a
\class{HRESULT} value.  These are long values containing error or
success codes.  In case the function returns an error \class{HRESULT}
value, a \class{WindowsError} is raised.  The GIL is released during the
duration of function call.
\end{quote}

\var{pydll}
\begin{quote}

This loader allows to call functions in libraries using the
\emph{Python} calling convention, for example Python C API functions.
The GIL is \emph{not} released during the function call, and the state
of the Python error flag is examined after the function returns.
If the error flag is set, the Python exception is raised.

ctypes provides a prefabricated instance of \var{pydll} exposing the
Python C api as the \var{pythonapi} symbol, you should however make
sure to set the correct \member{restype} for the functions you use.
\end{quote}


\subsubsection{Library objects\label{ctypes-library-objects}}

The library loaders create instances of \class{CDLL}, \class{WinDLL},
\class{OleDLL}, or \class{PyDLL} classes.  You can, however, also load a
library by constructing one of these classes by calling the
constructor with the pathname of the library and an optional \var{mode}
argument as described in the previous section.

Library objects implement \method{{\_}{\_}getattr{\_}{\_}} and \method{{\_}{\_}getitem{\_}{\_}} methods
that allow to access foreign functions by attribute access or
indexing.  The latter is useful if the name of the function is not a
valid Python identifier, or clashes with special Python method names
that start and end with two underscore characters.

Library objects have two private attributes: \member{{\_}name} is the pathname
of the library, \member{{\_}handle} is the handle to the library that
\code{dlopen} has returned.


\subsubsection{Foreign functions\label{ctypes-foreign-functions}}

Functions exported from loaded shared libraries (foreign functions)
can be accessed in two ways. The easiest way is to retrieve them as
attributes of library objects by name:
\begin{verbatim}
libc = cdll.find("c") # posix
libc = cdll.msvcrt # windows
# attribute access
atoi = libc.atoi
# alternative indexing notation
atoi = libc["atoi"]
\end{verbatim}

This creates an instance of a foreign function object, using the
calling convention specified by the library object \var{cdll}, bound to
the C library \code{atoi} function.  The C function is assumed to return
an integer (which is correct for \code{atoi}), and the argument types are
not specified (\code{atoi} expects a single \code{char *} argument).

If the library function returns a type different from \code{int}, the
\member{restype} attribute can be set to a ctypes type that describes the
return type, or to \code{None} meaning no return value (\code{void}).

The optional \member{argtypes} attribute can be set to a sequence of ctypes
types that the function expects.

If needed, the function can (as in C) be called with more arguments
than the length of the argtypes sequence.

The optional \member{errcheck} attribute can be set to a Python callable,
which can be used to validate and/or process the library function's return
value.  \member{errcheck} will be called with three arguments, after the
library function has returned:
\begin{verbatim}
errcheck(retval, function, arguments)
\end{verbatim}

\code{retval} is the value that the library function returned, converted
according to \member{restype}.  \code{function} is the ctypes function object
(libc.atoi in this case), and \code{arguments} is a tuple containing the
arguments that have been used to call \code{function}.  \member{errcheck}
should validate the library function result, raise an error if it
detects a failure, or return the needed return value otherwise.


\subsubsection{Function prototypes\label{ctypes-function-prototypes}}

Another way to access a function exported from shared libraries is to
first create a prototype by calling a factory function, specifying the
return type and the argument types.  The factory function itself
specifies the calling convention: \function{CFUNCTYPE} uses the standard C
calling convention, \function{WINFUNCTYPE} (Windows only) uses the stdcall
calling convention.  The factory function must be called with the
return type plus the argument types.  For the C \code{atoi} function one
would use \code{CFUNCTYPE(c{\_}int, c{\_}char{\_}p)}.

This returns a function prototype, which is a ctypes type representing
all functions that are compatible with the calling convention, return
type, and argument types.

The \function{CFUNCTYPE} and \function{WINFUNCTYPE} factory functions cache and
reuse the types they create in internal caches, so is is cheap to call
them over and over with the same or different arguments.

An instance of this function prototype, bound to a foreign library
function, can be created by calling the prototype with the name of the
function as string, and a loaded library:
\begin{verbatim}
proto = CFUNCTYPE(c_int, c_char_p)
atoi = proto("atoi", libc)
\end{verbatim}


\subsubsection{Parameter flags\label{ctypes-parameter-flags}}

It is possible to specify a third argument \var{paramflags} when calling
the prototype.  This is used to specify additional information for
each argument: direction of data transfer, the name, and a default
value.

A tuple with the same length as \member{argtypes} (the second argument in
the prototype call) must be used.  Each item in this tuple must be a
tuple, having either one, two, or three items.

The first item is the direction flag, an integer specifying if this is
an input (use \code{1}) or an output (use \code{2}) parameter.  The optional
second item is a string containing the parameter name, the optional
third item is a default value for the parameter.

If parameter names are specified, the function object created can be
called with named arguments in the usual way.  Arguments with default
values do not need to be specified when the function is called.

\code{out} parameter types must be pointer types.  When the function
object is called, ctypes will automatically create empty instances of
them, pass them to the library function, retrieve the value from them,
and return the value, if there is exactly one \code{out} parameter, or a
tuple of values, if there is more than one \code{out} parameter.  The
original foreign function return value is lost in this case (but see
below for how it can be retrieved).

If \var{paramflags} have been used in the prototype call, and an
\member{errcheck} attribute is also present, the \member{errcheck} callable will
be called with a fourth parameter \var{outargs}:
\begin{verbatim}
errcheck(retval, function, arguments, outargs)
\end{verbatim}

\var{outargs} is a tuple containing all the \code{out} parameters that
ctypes has created.  Without the \member{errcheck} function ctypes would
retrieve the values contained in these pointer objects, and return
them.  The \member{errcheck} function can let ctypes continue this
processing by returning the \var{outargs} tuple.  It could also return
something else, or raise an error if it detects that the library
function has failed.


\subsubsection{Callback functions\label{ctypes-callback-functions}}

ctypes is able to create C callable functions from Python callables.
This is useful because sometimes library functions need a callback
function parameter; the \function{qsort} C function is such an example.

Callback functions are created by first creating a function prototype
with a call to \function{CFUNCTYPE} or \function{WINFUNCTYPE}, specifying the return
type and the argument types that the callback function will receive.

Calling the prototype with a single Python callable will create and
return a C-callable function pointer or callback function.  Note that
this allows using prototypes as decorators creating callback
functions (Windows example):
\begin{verbatim}
@WINFUNCTYPE(BOOL, HWND, LPARAM)
def enumwindowsproc(hwnd, lParam):
    ....
    return True
\end{verbatim}

When a Python exception is raised in the Python callable, the return
value of the C callable function is undefined.

Important note: You must keep a reference to the callback AS LONG as
foreign code will call it!  Segfaults will result if the callback is
cleaned up by Python's garbage collector and external code then
tries to call it.

Callback objects can also be called from Python - this may be useful
for debugging.


\subsubsection{COM methods (Windows only)\label{ctypes-com-methods}}

XXX Should this be left undocumented?  Mentioned for completeness.

The prototypes created by \function{WINFUNCTYPE} can be called with a
positive small integer \var{index}, a string \var{name}, an optional
\var{paramflags} tuple, and a optional \var{iid} parameter.

This creates a function object wrapping a COM method.  \var{index} is
the index into the COM object's virtual function table, \var{name} is
the name of the COM method (only useful for debugging), \var{paramflags}
has the same meaning as for normal function objects, and \var{iid} is a
string or buffer containing the interface id of the COM interface
this method belongs to.  \var{iid} is used to get extended COM error
information in case the method returns a FAILED ''HRESULT`` value.

Note that COM methods expect an additional first argument that is NOT
listed in the prototypes \member{argtypes} when they are called: this must
be the integer address of a COM interface pointer.


\subsubsection{Simple types\label{ctypes-simple-types}}

Simple types have some special behaviour: When they are accessed as
structure or union fields, items of array instances, or as foreign
function return values, they are transparently converted from and to
the native Python types int, long, string, and unicode.

This is \emph{not} the case for subclasses of simple data types, so while a
\class{c{\_}void{\_}p} type is transparently converted from and to Python
integer or long, a subclass of c{\_}void{\_}p is \emph{not} converted.  This
allows you to define new behaviour almost completely.


\subsubsection{Class attributes of simple types\label{ctypes-class-attributes-of-simple-types}}

\code{{\_}{\_}ctype{\_}{\_}be{\_}{\_}}, \member{{\_}{\_}ctype{\_}le{\_}{\_}}
\begin{quote}

If the type supports different byte order (pointer types do NOT
support this), \member{{\_}{\_}ctype{\_}be{\_}{\_}} and \member{{\_}{\_}ctype{\_}le{\_}{\_}} are types
with bug endian and little endian byte order.  For example,
\code{c{\_}int.{\_}{\_}ctype{\_}be{\_}{\_}} is an integer type with the memory block in
big endian byte order.
\end{quote}

\member{{\_}type{\_}}
\begin{quote}

Implementation artifact: the typecode for this type, a single
character string code compatible to what the \code{struct} module uses.
Additional characters are used for types that the \code{struct} module
does not support.
\end{quote}


\subsubsection{Class methods of simple types\label{ctypes-class-methods-of-simple-types}}

(To be exact, these are not class methods, instead these are methods
of the metaclass.  The most prominent difference to classmethods is
that you can call these methods on the class, but not on the instance
of the simple type.)

\member{{\_}{\_}ctypes{\_}from{\_}outparam{\_}{\_}}
\begin{quote}

TBD
\end{quote}

\method{from{\_}address}
\begin{quote}

TBD
\end{quote}

\method{from{\_}param}
\begin{quote}

This class method is used to adapt function parameters.  If a type
is specified in a function's argtypes sequence, in a function call
the \code{from{\_}param(arg)} method will be called with the actual
argument, and the result will be passed to the foreign function
call as a parameter.

\method{from{\_}param} usually returns an internal object that you cannot
use in Python code - it only makes sense to pass this object to
foreign functions.

On one hand, \method{from{\_}param} is a performance optimization - it
allows you to pass Python integers to function calls expecting a
\class{c{\_}int} argument type, without having to create a full-featured
\class{c{\_}int} instance.

On the other hand, \method{from{\_}param} can adapt other objects to
parameters.  XXX explain the automatic \function{byref} call for byref
arguments.
\end{quote}

\method{in{\_}dll}
\begin{quote}

TBD
\end{quote}


\subsubsection{Instance attributes of simple types\label{ctypes-instance-attributes-of-simple-types}}

\code{value}
\begin{quote}

Allows to get or set the current value of the object.  For simple
types, this is always a native Python object like integer, long,
string, unicode, or None.
\end{quote}

\member{{\_}objects} (never modify this)
\begin{quote}

Implementation artifact: a Python object keeping references to
other objects which must be kept alive.  Never modify anything on
the returned object. XXX Should probably not be exposed.
\end{quote}

\member{{\_}b{\_}base{\_}} (readonly)
\begin{quote}

Implementation artifact: the base object owning the memory block
(if any).
\end{quote}

\member{{\_}b{\_}needsfree{\_}} (readonly)
\begin{quote}

Implementation artifact: does this object have to free its memory
block on destruction.
\end{quote}

\member{{\_}as{\_}parameter{\_}} (readonly)
\begin{quote}

Implementation artifact (?): how to pass this object as a function
parameter.
\end{quote}


\subsubsection{Numeric types\label{ctypes-numeric-types}}

Integer types are \class{c{\_}byte}, \class{c{\_}short}, \class{c{\_}int}, \class{c{\_}long},
\class{c{\_}longlong} and their unsigned variants \class{c{\_}ubyte}, \class{c{\_}ushort},
\class{c{\_}uint}, \class{c{\_}ulong} and \class{c{\_}ulonglong}, floating point types are
\class{c{\_}float} and \class{c{\_}double}.

The constructor and the \method{from{\_}param} class method accept a Python
integer for integer types, a Python float for floating point types.

On 32-bit platforms where sizeof(int) == sizeof(long), \class{c{\_}int} is an
alias for \class{c{\_}long}, on 64-bit platforms where sizeof(long) ==
sizeof(long long), \class{c{\_}long} is an alias for \class{c{\_}longlong}.


\subsubsection{Character types\label{ctypes-character-types}}

Character types are \class{c{\_}char} and \class{c{\_}wchar}, representing the C
\code{char} and \code{wchar{\_}t} types.

The constructor and the \method{from{\_}param} class method accept a single
character Python string or unicode string.  Conversion between string
and unicode, if needed, is done according to the ctypes
encoding/decoding rules.


\subsubsection{Pointer types\label{ctypes-pointer-types}}

The only simple pointer type is \class{c{\_}void{\_}p}, which represents the C
\code{void *} data type.  \class{c{\_}void{\_}p} can also be written as
\code{POINTER(None)}.

The constructor accepts one optional argument, which must be an
integer or long (interpreted as an address), or \code{None}.

The \method{from{\_}param} class method accepts everything that could be used
as a pointer.  XXX Should accept objects using the buffer interface as
well.

The \code{value} attribute accepts and returns None or integer.

XXX Shouldn't the constructor accept the same types as from{\_}param?


\subsubsection{String types\label{ctypes-string-types}}

ctypes has the \class{c{\_}char{\_}p} and \class{c{\_}wchar{\_}p} types which represent
const pointers to zero terminated strings in C: \code{const char *} and
\code{const wchar{\_}t *}.  Since strings and Unicode instances are
immutable, these types should be considered readonly: do not pass them
to functions that write into the buffer.

The constructor accepts one optional argument, which must be a Python
or unicode string, an integer, or \code{None}.

The \method{from{\_}param} class method accepts a string or a Unicode string,
as well as \code{None}.  Conversion between string and Unicode, if
needed, is done according to the ctypes encoding/decoding rules.

XXX Why does the constructor accept an integer, and from{\_}param doesn't?


\subsubsection{Structure and union types\label{ctypes-structure-union-types}}

ctypes provides the abstract base classes \class{Structure} and \class{Union}
to define structure and union types.  Subclasses must at least define
a \member{{\_}fields{\_}} attribute.


\subsubsection{Defining field names and types\label{ctypes-defining-field-names-types}}

\member{{\_}fields{\_}} must be a sequence of tuples.  The first item of each
tuple is a string specifying the name of the structure/union field.
The second item must by a ctypes type.

A descriptor will be created for each field, allowing you to access the
field's contents from instances.  Accessed from the class, the fields
expose readonly \code{.offset} and \code{.size} attributes.  \code{offset} is
the byte-offset of the field from the beginning of the
structure/union, \code{size} is the number of bytes the field contains.

A simple example is a POINT structure containing integer fields named
\code{x} and \code{y}:
\begin{verbatim}
class Point(Structure):
    _fields_ = [("x", c_int),
                ("y", c_int)]
\end{verbatim}


\subsubsection{Field alignment\label{ctypes-field-alignment}}

Normally fields are aligned in the same way as the host's C compiler
would do it.  This native alignment can be overridden by setting a
\member{{\_}pack{\_}} attribute in the type.  It must be a small positive integer
which is the maximum field alignment.


\subsubsection{Bit fields\label{ctypes-bit-fields}}

Integer fields support bit sizes.  The bit-size must be specified as
the third item of the \member{{\_}fields{\_}} tuple.  Bit fields are constructed
in the same way the host's C compiler does it.  For bit fields, the
field descriptor's \code{.size} attribute contains the number of bits in
the high word, and the bit offset from the beginning of the structure in
the low word.  XXX is that correct?


\subsubsection{Recursive data types\label{ctypes-recursive-data-types}}

To define recursive types, it is possible to assign the \member{{\_}fields{\_}}
value \emph{after} the class statement.  Here is an example of a linked
list data structure, which contains a pointer to itself:
\begin{verbatim}
class Node(Structure):
    pass
Node._fields_ = [("next", POINTER(Node)),
                 ("value", ...)]
\end{verbatim}

\member{{\_}fields{\_}} must be set, and cannot be changed, after the type is
used for the first time.


\subsubsection{Byte order\label{ctypes-byte-order}}

It is possible to create Structure and Union types using non-native
byte order by using the \class{BigEndianStructure},
\class{LittleEndianStructure}, \class{BigEndianUnion}, and
\class{LittleEndianUnion} base classes.  Structures and Unions with
non-native byte order do \emph{not} support pointer fields.


\subsubsection{Builtin functions\label{ctypes-builtin-functions}}

\code{addressof(object)}
\begin{quote}

Returns the address of a ctypes instance as an integer.
\end{quote}

\code{alignment(type{\_}or{\_}object)}
\begin{quote}

Returns the alignment requirements in bytes of a ctypes type or
instance.
\end{quote}

\code{byref(object)}
\begin{quote}

Returns a light-weight pointer to a ctypes instance.  The returned
object can only be used as function call parameter.  Behaves the
same as calling \code{pointer(object)}, but is a lot faster.  Same as
\code{{\&}object} in C.
\end{quote}

\code{cast(object, typ)}
\begin{quote}

This function is similar to the cast operator in C.  Returns a new
instance of \code{type} which shares the memory block of \code{object}.
\code{typ} must be a pointer type.
\end{quote}

\code{CFUNCTYPE(restype, *argtypes)}
\begin{quote}

Create a function prototype using the C calling convention.
\end{quote}

\code{create{\_}string{\_}buffer(init, size=None)}
\begin{quote}

Convenience function to create a mutable character buffer.

\var{init} must be a string.  If \code{size} is supplied it must be a
positive integer that specifies the size of the buffer, otherwise
the length of the \var{init} string is used.
This function returns a ctypes array of characters \class{c{\_}char}.
\end{quote}

\code{create{\_}unicode{\_}buffer(init, size=None)}
\begin{quote}

Convenience function to create a mutable unicode buffer.

\var{init} must be a unicode string.  If \code{size} is supplied it
must be a positive integer that specifies the number of characters
in the buffer, otherwise the length of the \var{init} string is
used.  This function returns a ctypes array of characters \class{c{\_}wchar}.
\end{quote}

\function{DllCanUnloadNow()}, \code{DllGetClassObject(rclsid, riid, ppv)} (Windows only)
\begin{quote}

Functions used to implement COM servers.
\end{quote}

\code{FormatError({[}code{]})} (Windows only)
\begin{quote}

Returns a textual description of the error code, or the last error
code set by Windows.
\end{quote}

\function{GetLastError()} (Windows only)
\begin{quote}

Returns the last error code set by Windows.
\end{quote}

\code{memmove(dst, src, count)}
\begin{quote}

Same as the standard C \function{memmove} library function: copies
\var{count} bytes from \code{src} to \var{dst}.  \var{dst} and \code{src} must
be integers or anything else that can be converted into a pointer.
\end{quote}

\code{memset(dst, c, count)}
\begin{quote}

Same as the standard C \function{memset} function.  Fills the memory block
at address \var{dst} with \var{count} bytes of value \var{c}.  \var{dst} must be
an integer specifying an address, or a ctypes instance.
\end{quote}

\code{pointer(object)}
\begin{quote}

This function creates a new pointer instance, pointing to the
supplied argument which must be an instance of a ctypes type.  The
return pointer is of type \code{POINTER(type(object))}.  If you have
a ctypes instance, and you want to pass the address of it to a
function call, you should use \code{byref(object)} instead which is
much faster.

NULL pointer instances are boolean``False``, so to check for a
NULL pointer do this:
\begin{verbatim}
# assuming ptr is in ctypes pointer instance
if ptr:
    print "Non-NULL pointer instance"
else:
    print "NULL pointer instance"
\end{verbatim}
\end{quote}

\code{POINTER(cls)}
\begin{quote}

This factory function creates and returns a new ctypes type.
Pointer types are cached, so calling this function is cheap.

To create a \code{NULL} pointer instance, call the created type
without an argument:
\begin{verbatim}
null_ptr = POINTER(c_int)()
\end{verbatim}
\end{quote}

\code{set{\_}conversion{\_}mode(encoding, errors)}
\begin{quote}

This function sets the encoding/decoding rules which are used when
ctypes has to convert between unicode and byte strings.  It
returns the previous encoding, as well as a tuple of any errors.
If not set, default conversions are used:
On Windows, \code{msbc, ignore} , on other systems, \code{ascii, strict}.
\end{quote}

\code{sizeof(type{\_}or{\_}object)}
\begin{quote}

Returns the size in bytes of a ctypes type or instance memory
buffer.  Does the same as the C sizeof() function.
\end{quote}

\code{string{\_}at(addr{[}, size{]})}
\begin{quote}

This function does the same as the Python \function{PyString{\_}FromString} /
\function{PyString{\_}FromStringAndSize} C api functions.
\end{quote}

\code{WinError(code=None, descr=None)}
\begin{quote}

XXX This is probably the worst named thing in ctypes!

This function creates a \class{WindowsError} instance.  If \var{code} is
not specified, GetLastError() is called to determine the error
code.  If \code{descr} is not specified, \function{FormatError} is called to
get a textual description of the error.
\end{quote}

\code{WINFUNCTYPE(restype, *argtypes)} (Windows only)
\begin{quote}

Create a function prototype using the {\_}{\_}stdcall calling convention
(on Windows), or using the C calling convention (on Windows CE).
\end{quote}

\code{wstring{\_}at(addr{[}, size{]})}
\begin{quote}

This function does the same as the Python \function{PyUnicode{\_}FromWideString}
C api function.  If \code{size} is not specified, \code{wcslen} is used
to determine the string length.
\end{quote}


\subsubsection{Deprecated functions\label{ctypes-deprecated-functions}}

These deprecated functions are still supported for backwards
comatibility, they should not be used for new code:

\code{c{\_}buffer(init, size=None)}
\begin{quote}

Deprecated.  Use \function{create{\_}string{\_}buffer()} instead.
\end{quote}

\code{ARRAY(cls, len)}
\begin{quote}

Deprecated.  Use \code{cls * len} instead.
\end{quote}

\code{SetPointerType(pointer{\_}class, cls)}
\begin{quote}

Deprecated.
\end{quote}

